using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Xml;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

        XmlDocument answers = new XmlDocument();


        if (!IsPostBack)
        {

            string surveyQueryString = Request.QueryString["Survey"];
            this.Title = ConfigurationManager.AppSettings["SurveyEditPageTitle"] + ": " + surveyQueryString;;

            if (surveyQueryString == null)
            {
                Response.Redirect("~/Restricted/Error.aspx");
                return;
            }

            bool canUpdate = false;

            XmlDocument users = new XmlDocument();
            users.Load(ConfigurationManager.AppSettings["UsersLocation"]);
            XmlNodeList usersList = users.SelectNodes("Users/User");
            foreach (XmlNode user in usersList)
            {

                if (user.Attributes["username"].Value == User.Identity.Name)
                {
                    if (user.Attributes["admin"].Value == "true")
                    {
                        XmlDocument surveys = new XmlDocument();
                        surveys.Load(ConfigurationManager.AppSettings["SurveysLocation"]);
                        XmlNodeList surveyList = surveys.SelectNodes("Surveys/Survey");
                        foreach (XmlNode survey in surveyList)
                        {
                            if (surveyQueryString == survey.InnerXml)
                            {
                                canUpdate = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        XmlNodeList surveyList = user.SelectNodes("Surveys/Survey");
                        foreach (XmlNode survey in surveyList)
                        {
                            if (surveyQueryString == survey.InnerXml)
                            {
                                canUpdate = true;
                                break;
                            }
                        }
                    }
                    if (canUpdate)
                        break;
                }
            }

            if (!canUpdate)
            {
                Response.Redirect("~/Restricted/Error.aspx");
                return;
            }


            WikiTools.Access.Wiki wiki = new WikiTools.Access.Wiki(ConfigurationManager.AppSettings["mWikiRootPath"], ConfigurationManager.AppSettings["mWikiCachePath"], ConfigurationManager.AppSettings["mWikiUsername"], ConfigurationManager.AppSettings["mWikiPassword"]);
//            wiki.Login(ConfigurationManager.AppSettings["mWikiUsername"], ConfigurationManager.AppSettings["mWikiPassword"]);


            //create if it does not exist
            wiki.CreatePage(ConfigurationManager.AppSettings["mWikiRootSurveyPage"] + " - " + surveyQueryString, "new page", false);

            
            WikiTools.Access.Page page = new WikiTools.Access.Page(wiki, ConfigurationManager.AppSettings["mWikiRootSurveyPage"] + " - " + surveyQueryString);

            ViewState["Answers"] = page.Text.Replace("<!--", "").Replace("-->", "").Replace("== ", "").Replace(" ==", "");

        }

        try { answers.LoadXml(ViewState["Answers"].ToString()); }
        catch { }

        XmlDocument questions = new XmlDocument();
        questions.Load(ConfigurationManager.AppSettings["QuestionsLocation"]);
        XmlNodeList questionList = questions.SelectNodes("Questions/Question");

        int index = 0;

        foreach (XmlNode question in questionList)
        {


            string id = question.Attributes["id"].Value;

            Label label = new Label();
            label.Text = "<b>" + question.InnerXml + "</b>";
            label.ID = "label" + id;

            TextBox textBox = new TextBox();
            textBox.TextMode = TextBoxMode.MultiLine;
            textBox.Rows = 5;
            textBox.Width = 600;
            textBox.Text = GetAnswer(answers.SelectNodes("Answers/Answer"), id);
            textBox.ID = "text" + id;

            Literal lineBreak1 = new Literal();
            lineBreak1.Text = "<br/>";
            Literal lineBreak2 = new Literal();
            lineBreak2.Text = "<br/>";
            Literal lineBreak3 = new Literal();
            lineBreak3.Text = "<br/>";


            this.QuestionsPlaceHolder.Controls.Add(label);
            this.QuestionsPlaceHolder.Controls.Add(lineBreak1);
            this.QuestionsPlaceHolder.Controls.Add(textBox);
            this.QuestionsPlaceHolder.Controls.Add(lineBreak2);
            this.QuestionsPlaceHolder.Controls.Add(lineBreak3);

            index++;
        }


    }
    private string GetAnswer(XmlNodeList nodeList, string id)
    {
        string retValue = "";

        foreach (XmlNode node in nodeList)
        {
            if (node.Attributes["id"].Value == id)
            {
                retValue = node.InnerXml;
                break;
            }
        }

        return retValue;
    }
    protected void SubmitButton_Click(object sender, EventArgs e)
    {

        string surveyQueryString = Request.QueryString["Survey"];

        WikiTools.Access.Wiki wiki = new WikiTools.Access.Wiki(ConfigurationManager.AppSettings["mWikiRootPath"], ConfigurationManager.AppSettings["mWikiCachePath"], ConfigurationManager.AppSettings["mWikiUsername"], ConfigurationManager.AppSettings["mWikiPassword"]);

        //wiki.Login(ConfigurationManager.AppSettings["mWikiUsername"], ConfigurationManager.AppSettings["mWikiPassword"]);

        WikiTools.Access.Page page = new WikiTools.Access.Page(wiki, ConfigurationManager.AppSettings["mWikiRootSurveyPage"] + " - " + surveyQueryString);

        string wikiText = "";
        wikiText += "<!--<?xml version=\"1.0\" encoding=\"utf-8\" ?>-->";
        wikiText += "<!--<Answers>-->";


        foreach (Control control in this.QuestionsPlaceHolder.Controls)
        {
            if (control.GetType() == typeof(Label))
            {
                wikiText += "<!--<RefQuestion id=\"" + ((Label)control).ID.Replace("label","") + "\">-->";
                wikiText += "== " + ((Label)control).Text.Trim() + " ==" + Environment.NewLine;
                wikiText += "<!--</RefQuestion>-->";
            }
            if (control.GetType() == typeof(TextBox))
            {
                wikiText += "<!--<Answer id=\"" + ((TextBox)control).ID.Replace("text","") + "\">-->";
                wikiText += ((TextBox)control).Text.Trim() + Environment.NewLine;
                wikiText += "<!--</Answer>-->";
            }
        }

        wikiText += "<!--</Answers>-->";

        page.SetText(wikiText);

        Response.Redirect("Done.aspx");


    }
    protected void LogoutButton_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        FormsAuthentication.RedirectToLoginPage();
    }
    protected void BackToSurveysButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Restricted/SurveysAvailable.aspx");
    }
}
